<?php
namespace app\widget\controller;

use tp5_lib\common\controller\BaseController;
use DataWidget\entity\ActionLink;
use DataWidget\widget\ListWidget;
use DataWidget\entity\PageLink;
use DataWidget\widget\FormWidget;
use DataWidget\widget\FilterWidget;
use DataWidget\extensible\ArrayFilterHandler;

class RecordController extends BaseController
{
    protected $fields=[
        ["code"=>"id","title"=>"ID","type"=>"number"],
        ["code"=>"title","title"=>"标题"],
        ["code"=>"describe","title"=>"描述"],
        ["code"=>"content","title"=>"内容"],
        ["code"=>"audit","title"=>"审核","type"=>"checkbox","options"=>"已审核|未审核"],
        ["code"=>"type","title"=>"类型","type"=>"select","options"=>"0,私有;1,保护;2,公开"],
        ["code"=>"tag","title"=>"标签","type"=>"multi_select","options"=>"0,重要;1,紧急;2,通知"],
        ["code"=>"create_time","title"=>"创建时间","type"=>"datetime-local"],
        ["code"=>"number","title"=>"数字","type"=>"number"],
        ["code"=>"range","title"=>"百分比","type"=>"range","min"=>"100","max"=>"200","step"=>"10"],
    ];
    protected $filters=[
        ["code"=>"id","title"=>"ID","describe"=>"ID","type"=>"equal","asso_field"=>"id"],
        ["code"=>"search","title"=>"查找","describe"=>"标题、描述或内容","type"=>"like","asso_field"=>"id,title,describe,content"],
        ["code"=>"date","title"=>"日期","describe"=>"创建日期","type"=>"date","asso_field"=>"create_time"],
        ["code"=>"time","title"=>"时间","describe"=>"创建时间","type"=>"datetime_range","asso_field"=>"create_time"],
    ];
    protected $data=[
        ["id"=>1,"title"=>"纪录模板","describe"=>"edfefew","content"=>"这是一条记录","type"=>"0","tag"=>"0,1","create_time"=>"1561626989"]
    ];
    public function index()
    {
        if(!$data=cache("record")){
            $data=$this->data;
            cache("record",$data);
        }
        $handler=new ArrayFilterHandler($data);
        $map=include __DIR__ . "/../view/base/_map.php";
        $filter=FilterWidget::alloc()->setMap($map["filter"])->setHandler($handler)->setInputs($this->filters)->input(input());
        $list=ListWidget::alloc()->setMap($map["field"])->loadFields($this->fields)->setData($handler->data)
        ->addAction("修改",function($item){
            return url("edit",["id"=>$item["id"]]);
        })
        ->setItemActions(function($item){
            return [
                ActionLink::create("复制",url("copy",["id"=>$item["id"]])),
                ActionLink::create("删除",url("delete",["id"=>$item["id"]]),"确认删除这条数据?")
            ];
        })
        ->addFlag("selectable");

        //绑定模板和数据
        return $this->fetch('',[
            "tabs"=>PageLink::fillList([
                ["title"=>"列表","href"=>url("index"),"active"=>true],
                ["title"=>"新建","href"=>url("add")],
            ]),
            "list"=>$list->toArray(),
            "entire_actions"=>[ActionLink::build("重置",url('reset'),"确认重置数据?","数据将被重置为默认数据")],
            "multi_actions"=>ActionLink::fillList([
                ["title"=>"删除","href"=>url("delete"),"confirm"=>"确认删除选中的数据?"],
            ]),
            "filter"=>$filter->toArray(),
            "filter_actions"=>ActionLink::fillList([
                ["title"=>"删除","href"=>url("delete"),"confirm"=>"确认删除所有匹配的数据?"],
            ]),
        ]);
    }
    public function reset()
    {
        cache("record",$this->data);
        $this->redirect('index');
    }
    public function add()
    {
        $map=include __DIR__ . "/../view/base/_map.php";
        $form=FormWidget::alloc()->setMap($map["field"])->setInputs($this->fields)->setAction(url('insert'),"提交");
        return $this->fetch('edit',['form'=>$form->toArray()]);
    }
    public function copy()
    {
        if(!$id=input("id")) $this->error('ID不能为空');
        if(!$data=cache('record')) $this->error('数据为空');
        $record=null;
        foreach($data as $item){
            if($item["id"] == $id){
                $record=$item;
            }
        }
        if($record === null) $this->error('指定数据不存在');

        $map=include __DIR__ . "/../view/base/_map.php";
        $form=FormWidget::alloc()->setMap($map["field"])->setInputs($this->fields)->setValues($record)->setAction(url('insert'),"提交");
        return $this->fetch('edit',['form'=>$form->toArray()]);
    }
    public function edit()
    {
        if(!$id=input("id")) $this->error('ID不能为空');
        if(!$data=cache('record')) $this->error('数据为空');
        $record=null;
        foreach($data as $item){
            if($item["id"] == $id){
                $record=$item;
            }
        }
        if($record === null) $this->error('指定数据不存在');

        $map=include __DIR__ . "/../view/base/_map.php";
        $form=FormWidget::alloc()->setMap($map["field"])->setInputs($this->fields)->setValues($record)->setAction(url('update'),"提交")->toArray();

        return $this->fetch('edit',[
            'form'=>$form,
        ]);
    }
    public function update()
    {
        $map=include __DIR__ . "/../view/base/_map.php";
        $data=FormWidget::alloc()->setMap($map["field"])->setInputs($this->fields)->getInput(input());
        if(!$records=cache('record')) $this->error('数据为空');

        $record=null;
        foreach($records as $index => $item){
            if($item["id"] == $data["id"]){
                $record=$item;
                break;
            }
        }
        if($record === null) $this->error('指定数据不存在');
        $records[$index]=$data;
        cache('record',$records);
        $this->redirect('index');
    }
    public function insert()
    {
        $map=include __DIR__ . "/../view/base/_map.php";
        $data=FormWidget::alloc()->setMap($map["field"])->setInputs($this->fields)->getInput(input());
        if(!$records=cache('record')) $this->error('数据为空');

        do{
            $unique=true;
            foreach($records as $record){
                if($record["id"] == $data["id"]){
                    $data["id"]++;
                    $unique=false;
                    break;
                }
            }
        }
        while($unique===false);
        
        $data["create_time"]=time();

        $records[]=$data;
        cache('record',$records);
        $this->redirect('index');
    }
    public function delete()
    {
        $data=input();
        if(!$records=cache('record')) $this->error('数据为空');
        if(isset($data["id"])){
            foreach($records as $index => $item){
                if($item["id"] == $data["id"]){
                    unset($records[$index]);
                    break;
                }
            }
        }
        if(isset($data["select"])){
            foreach($records as $index => $item){
                if(in_array($item["id"],$data["select"])) unset($records[$index]);
            }
        }
        cache('record',$records);
        $this->redirect('index');
    }
}
